package com.hjjt.baselib.permission

import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commit

/**
 *
 * @ProjectName:    IntelligentTerminal
 * @Package:        com.hjjt.baselib.permission
 * @ClassName:      HJPermission
 * @Description:
 * @Author:         孙浩
 * @CreateDate:     2022/8/8 8:33
 */
object HJPermission {

    val TAG = javaClass.simpleName

    var permissionFragment: PermissionFragment? = null

    var granted: (() -> Unit)? = null
    var error: ((dinePermissionList: List<String>) -> Unit)? =
        null

    fun requestPermission(activity: FragmentActivity, vararg permission: String):HJPermission {
        createFragmentByManager(activity.supportFragmentManager, *permission)
        return this
    }

    fun requestPermission(fragment: Fragment, vararg permission: String) :HJPermission{
        createFragmentByManager(fragment.childFragmentManager, *permission)
        return this
    }

    private fun createFragmentByManager(
        fragmentManager: FragmentManager,
        vararg permission: String
    ) {
        permissionFragment = PermissionFragment.newInstance(*permission).apply {
            callBack = {
                val permissionDineList = it.filter {
                    !it.value
                }
                if (permissionDineList.isNotEmpty()) {
                    error?.invoke(permissionDineList.map { it.key }.toList())
                } else {
                    granted?.invoke()
                }
            }
        }
        fragmentManager.commit {
            add(permissionFragment!!, TAG)
        }
    }
}

fun FragmentActivity.requestPermissionEX(
    vararg permission: String,
    granted: (() -> Unit),
    error: ((dinePermissionList: List<String>) -> Unit)
) {
    HJPermission.requestPermission(this, *permission).apply {
        this.granted = granted
        this.error = error
    }
}

fun Fragment.requestPermissionEX(
    vararg permission: String,
    granted: (() -> Unit),
    error: ((dinePermissionList: List<String>) -> Unit)
) {
    HJPermission.requestPermission(this, *permission).apply {
        this.granted = granted
        this.error = error
    }
}